import Vue from 'vue'
import store from './store'
import App from './App'
import * as otherApi from './config/api.js'


import * as Common from './config/common.js'
import * as Db from './config/db.js'
import * as Config from './config/config.js'
import Json from './Json' //测试用数据
/**
 *  因工具函数属于公司资产, 所以直接在Vue实例挂载几个常用的函数
 *  所有测试用数据均存放于根目录json.js
 *
 *  css部分使用了App.vue下的全局样式和iconfont图标，有需要图标库的可以留言。
 *  示例使用了uni.scss下的变量, 除变量外已尽量移除特有语法,可直接替换为其他预处理器使用
 */
const msg = (title, duration=1500, mask=false, icon='none')=>{
	//统一提示方便全局修改
	if(Boolean(title) === false){
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon: 'none'
	});
}
const json = type=>{
	//模拟异步请求数据
	return new Promise(resolve=>{
		setTimeout(()=>{
			resolve(Json[type]);
		}, 500)
	})
}

const prePage = ()=>{
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
    // #ifdef H5
    return prePage;
    // #endif

	return prePage.$vm;
}

/**
 * 跟apiclound-app内容进行交互
 * 
 * @param name   {String} 事件名称，需要在APP提前做监听，参考index/tab_shop.html中44-49行，必传参数
 * @param params {Object} 发送到APP的数据，非必填参数
 */
const cloudEvent = (name, params = {}) => {
    if(!name) {
        msg('cloudEvent方法name参数错误,不能为空');
        return;
    }
    try {
       api.sendEvent({
           name: name, 
           extra: params 
       }); 
    }catch(e) {
        // uni.reLaunch({
        //     url: prePage()
        // })
        // alert(e);
    }
}

/**
 * APP调用的方法，设置用户身份 1 学生 2 老师
 */
window.setUserInfo = (authorization = '', userType = '') => {
    // alert(authorization);
    try {
        if(localStorage.getItem('authorization') != authorization) {
            uni.switchTab({
            	url: `/pages/langwen/index`
            });
        }
        localStorage.setItem('userType', userType);
        localStorage.setItem('authorization', authorization);
    }catch(e) {
        
    }
}
/**
 * 打开商品详情
 */
window.fnOpenGoodsDetail = (id, shareTeacher) => {
    if(id) {
        uni.navigateTo({
        	url: `/pages/langwen/detail?id=${id}&shareTeacher=${shareTeacher}`
        });
    }
}

/**
 * 打开商品分类
 */
window.fnOpenGoodsCatagory = (id, name) => {
    if(id) {
        // 路径
        var url = '/pages/langwen/sort2';
        // 参数 
        var param = {
            lev1Id: id, // 选中一级分类
        	lev1Title: name, // 选中一级标题
            lev2: 0, // 选中二级分类
            lev3: '' // 选中三级分类
        };
        uni.navigateTo({
            url: `${url}?param=${encodeURIComponent(JSON.stringify(param))}`
        });
    }
}

/**
 * 打开活动详情
 * type 3 基本营销 4 满赠营销
 */
window.fnOpenGoodsActivity = (id, name, type) => {
    if(id) {
        // 路径
        var url = '/pages/langwen/activityDetail';
        // 参数 
        var param = { id, name, type };
        uni.navigateTo({
            url: `${url}?param=${encodeURIComponent(JSON.stringify(param))}`
        });
    }
}

/**
 * 再来一单，订单预览
 */
window.fnOrderGotoBuy = () => {
    let data = uni.getStorageSync('langwenabc');
    if(data) {
        
        try {
            uni.navigateTo({
                url: `/pages/langwen/confirm?param=${data}`
            });
            uni.removeStorage({
                key: 'langwenabc'
            })
        }catch(e) {
            // alert('fnOrderGotoBuy>>>>'+e);
        }
    }
}

window.fnSetAppLabel = () => {
    uni.setStorage({
        key: 'langwen',
        data: 'langwenApp'
    });
}

window.fnSetShopOnIndex = () => {
    uni.switchTab({
        url: `/pages/langwen/index`
    });
}

/**
 * 获取用户类型 1 学生 2 老师
 */
const fnGetUserType = () => {
    return localStorage.getItem('userType');
}

/**
 * 订单支付
 * 
 * @param {String} orderNo  订单号，必填参数 
 * @param {String} price    支付金额，保留两位小数的字符串格式
 */
const orderPay = (orderNo, price, id) => {
    // 到APP中进行支付
    api.sendEvent({
        name: 'H5_gotoPay',
        extra: {  orderNo, price, id }
    });
}

/**
 * 选择地址
 * 
 * @param {String}  id  已经选择的地址id
 */
const handleSelectAddress = (id) => {
    // 去APP选择地址
    api.sendEvent({
        name: 'H5_gotoSelectAdress',
        extra: { id }
    })
}

/**
 * 分享
 *  
 * @param {String} id 商品ID，唯一标志，必填
 */
const shareToApp = (id) => {
    api.sendEvent({
        name: 'shareGoods',
        extra: { id }
    });
}
Vue.prototype.$otherApi = otherApi;
Vue.prototype.$common = Common;
Vue.prototype.$db = Db;
Vue.prototype.$config = Config;
Vue.config.productionTip = false;
Vue.prototype.$fire = new Vue();
Vue.prototype.$store = store;
Vue.prototype.$api = {msg, json, prePage};
Vue.prototype.$clound = {cloudEvent, fnGetUserType, shareToApp, orderPay, handleSelectAddress};

App.mpType = 'app'

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

Vue.filter('fnContentTime', function(_date) {
    var date = _date ? new Date(_date) : new Date();
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    return formatNumber(month) + "月" + formatNumber(day) + "日";
})

const app = new Vue({
    ...App
})
app.$mount()
